package com.blyat.xsoft.kernel.component.security.oauth2;

import com.blyat.xsoft.kernel.component.security.exception.SecureException;
import com.blyat.xsoft.kernel.component.security.exception.code.SecurityErrorResult;
import com.blyat.xsoft.kernel.restful.view.ResultModel;
import com.blyat.xsoft.kernel.util.ServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author syh
 * @date 2019/9/29
 * 匿名用户访问无权限资源时的异常
 **/
public class OauthAuthenticationEntryPoint extends OAuth2AuthenticationEntryPoint {

    private static final Logger logger = LoggerFactory.getLogger(OauthAuthenticationEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException {

        // 用户登录时身份认证未通过,不知道这个请求时哪里发起的。。。
        if ("/undefined".equals(request.getRequestURI())) return;


        if (ex instanceof BadCredentialsException) {
            logger.error("用户登录时身份认证失败:{}", request.getRequestURI(), ex);
            ServletUtil.writer(ResultModel.FAIL(new SecureException(SecurityErrorResult.USER_NOT_EXISTS)));
        } else if (ex instanceof InsufficientAuthenticationException) {
            logger.error("token无效:{}", request.getRequestURI(), ex);
            ServletUtil.writer(ResultModel.FAIL(new SecureException(SecurityErrorResult.ACCESS_DENIED)));
        } else {
            logger.error("认证失败:{}", request.getRequestURI(), ex);
            ServletUtil.writer(ResultModel.FAIL(new SecureException(SecurityErrorResult.INVALID_USER)));
        }

    }

}
